package com.hmo.automatic;

import android.content.Intent;
import android.os.Build;
import android.telecom.Call;
import android.telecom.InCallService;
import android.util.Log;

import androidx.annotation.RequiresApi;

@RequiresApi(api = Build.VERSION_CODES.M)
public class PhoneCallService extends InCallService {

    private static final String TAG = "来电服务";
    private Call.Callback callback = new Call.Callback() {
        @Override
        public void onStateChanged(Call call, int state) {
            super.onStateChanged(call, state);
//            switch (state) {
//                case Call.STATE_ACTIVE: {
//                    break; // 通话中
//                }
//                case Call.STATE_DISCONNECTED: {
//                    break; // 通话结束
//                }
//            }
        }
    };

    @Override
    public void onCallAdded(Call call) {
        super.onCallAdded(call);
        Log.e(TAG, call.toString());
        call.registerCallback(callback);
        PhoneCallManager.call = call; // 传入call
//        CallType callType = null;
//        call.getState();
//        if (call.getState() == Call.STATE_RINGING) {
//            callType = CallType.CALL_IN;
//        } else if (call.getState() == Call.STATE_CONNECTING) {
//            callType = CallType.CALL_OUT;
//        }
        Log.e(TAG, "onCallAdded: " );
        if (call.getState()==Call.STATE_RINGING) {
            Call.Details details = call.getDetails();
            String phoneNumber = details.getHandle().toString().substring(4)
                    .replaceAll("%20", ""); // 去除拨出电话中的空格
            Intent intent = new Intent(getBaseContext(), PhoneActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(Intent.EXTRA_MIME_TYPES, Call.STATE_RINGING);
            intent.putExtra(Intent.EXTRA_PHONE_NUMBER, phoneNumber);
            startActivity(intent);

        }
    }

    @Override
    public void onCallRemoved(Call call) {
        super.onCallRemoved(call);

        call.unregisterCallback(callback);
        PhoneCallManager.call = null;
    }
}